from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.goods.models import SKUImage, SKU
from apps.meiduo_admin.serializers.image import SKUImageModelViewSet
from apps.meiduo_admin.utils.MeiduoPage import PageNum
from celery_tasks.detail.tasks import generate_task

class ImageViewSet(ModelViewSet):
    pagination_class = PageNum
    queryset = SKUImage.objects.all().order_by('-id')
    serializer_class = SKUImageModelViewSet

    def create(self, request, *args, **kwargs):
        # 创建FastDFS连接对象

        client = Fdfs_client(settings.FASTDFS_CLIENT_CONF)

        # 获取前端传递的image文件
        image = request.data.get('image')
        sku_id=request.data.get('sku')
        # 上传图片到fastDFS
        res = client.upload_by_buffer(image.read())

        image_url = res['Remote file_id']

        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        sku = SKU.objects.get(pk=sku_id)
        if sku.default_image == '':
            sku.default_image = image_url
            sku.save()
        print(200)
        instance=self.get_serializer(img)
        return Response(instance.data,status=201)

    def update(self, request, *args, **kwargs):
        instance=self.get_object()
        sku_id=request.data.get('sku')
        image=request.data.get('image')

        client = Fdfs_client(settings.FASTDFS_CLIENT_CONF)
        client.delete_file(instance.image.name)
        res=client.upload_by_buffer(image.read())
        img_url=res['Remote file_id']
        instance.image=img_url

        instance.save()

        serializer=self.get_serializer(instance)
        return Response(serializer.data,status=201)
